<?php

require_once __DIR__ . '/../vendor/autoload.php';
include_once __DIR__ . '/config.php';

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

function httpPost(string $method, array $parameters, bool $encrypt = false): array
{
    if ($encrypt) {
        $params = filterAndEncryptParameterData($parameters);
    } else {
        $params = array_values($parameters);
    }

    $json = [
        'jsonrpc' => '2.0',
        'method'  => $method,
        'params'  => $params,
        'id' => 1,
    ];

    $client = new Client();
    $url = 'https://backend.straitchain.com/webclient/api/develop/straits/action';

    try {
        $response = $client->post($url, [
            RequestOptions::JSON => $json,
        ]);
        $result = json_decode($response->getBody()->getContents(), true);
    } catch (Exception $e) {
        var_dump('request error: ' . $e->getMessage());
        $result = [];
    }
    return $result;
}

function filterAndEncryptParameterData(array $parameters): array
{
    $values = [];
    foreach ($parameters as $val) {
        if (!is_null($val)) {
            $values[] = $val;
        }
    }

    $str = implode('&', $values);
    if ($str) {
        $str = $str . '&' . APP_KEY;
    } else {
        $str = APP_KEY;
    }
    $values[] = md5($str);

    return $values;
}